var myMap;
var pointsShown;
var placemarks;

var pointsInRoute = 0;

ymaps.ready(init);

function init () {
	initMap();
	initPlacemarks();
   
	// Mouse icon should be pointer always
    document.getElementsByClassName("ymaps-glass-pane ymaps-events-pane").
	item(0).addEventListener('mouseup', function(e) {
		this.style.cursor = "pointer";
	}, false);
}

function initMap() {
	var mapDiv = document.getElementById("map");
	mapDiv.style.width = (screen.width - 40)/2 + "px";

    myMap = new ymaps.Map("map", {
        center: [52.089261, 23.698397],
        zoom: 15
    });
    
    myMap.controls
	    // Кнопка изменения масштаба.
	    .add('zoomControl', { left: 5, top: 5 })
	    // Список типов карты
	    .add('typeSelector');
    
    document.getElementById("map").style.cursor = "pointer";
}

function initPlacemarks() {
	placemarks = new Array();
	var lat, lon, name, id;
	var count = document.getElementById("count").innerHTML;
	
	for (var i = 0; i < count; ++i) {
		id = document.getElementById((i+1) + "id").innerText;
	    lat = document.getElementById((i+1) + "lat").innerText;
	    lon = document.getElementById((i+1) + "lon").innerText;
	    name = document.getElementById((i+1) + "name").innerText;

	    placemarks[i] = new ymaps.Placemark([lat, lon], {
            hintContent: name
	    });
	    placemarks[i].id = id;
	    placemarks[i].name = name;
	    
	    myMap.geoObjects.add(placemarks[i]);
	}
	
	myMap.geoObjects.each(function (geoObject) {
		geoObject.events.add('click', function (e) {
			var input = document.createElement('input');
			input.className = 'hidden';				
			input.setAttribute("name", pointsInRoute++);
			input.setAttribute("value", geoObject.id);
			
			var span = document.createElement('span');
			span.className = 'point-in-route';
			span.setAttribute("value", geoObject.name);
			span.innerHTML = geoObject.name;
		
			document.getElementById("form").appendChild(input);
			document.getElementById("form").appendChild(span);
	    });
	});	
	pointsShown = true;
}


function showPoints() {
	var len = placemarks.length;
	if (!pointsShown) {		
		for (var i = 0; i < len; ++i) 
	        myMap.geoObjects.add(placemarks[i]);
	    pointsShown = true;
	    document.getElementById("showhide").setAttribute("value", "Hide points");
	} else {
		for (var i = 0; i < len; ++i) 
	        myMap.geoObjects.remove(placemarks[i]);
	    pointsShown = false;
	    document.getElementById("showhide").setAttribute("value", "Show points");
	}
}